﻿using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Text;
using WorkFlowCore.Common.Authentication.JWT;

namespace WorkFlowCore.Common.Authorization.JWT
{
    public static class AuthenticationJWTModule
    {
        public static AuthenticationBuilder AddCommonJwtBearer(this AuthenticationBuilder builder,Action<JWTAuthenticationOptions> opions=null)
        {
            var services = builder.Services;
            var config = new JWTAuthenticationOptions();
            if(opions!=null)opions.Invoke(config);
            services.AddSingleton(p => config);

            builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
             {
                 options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                 {
                     NameClaimType = JwtClaimTypes.Name,
                     RoleClaimType = JwtClaimTypes.Role,

                     ValidIssuer = JWTAuthenticationOptions.JwtClaimTypesIssuer,
                     ValidAudience = JWTAuthenticationOptions.JwtClaimTypesAudience,

                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.SecretKey))

                 };
             });

            services.AddScoped<JWTAuthenticationManager>();
            services.AddScoped(typeof(ICustomizationVerify), typeof(NullCustomizationVerify));

            return builder;
        }

        public static IApplicationBuilder UseAuthorizationJWTHandler(this IApplicationBuilder app)
        {
            JWTAuthenticationManager.InitAuthenticationSee();
            //从 头部和 请求参数整解析token数据
            app.UseMiddleware<AuthorizationMiddleware>();
            return app;

        }
    }
}
